package com.yige.service.mongoService

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.yige.common.DateUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.GoodsService
import org.springframework.stereotype.Service

/**
 * Created by sunhao on 2015/10/9 0009.
 */

@Service
class MongoGoodsService extends BasicMongoServiceImp implements GoodsService {

    @Override
    DBCollection getCollection() {
       return mongoTemplate.getCollection(SystemConstant.MONGODB_COL_GOODS)
    }

    @Override
    boolean storageGoods(String name, String storage_date, double cost, String info) {
        double price = 0
        Map<String, Object> goodsInfo = [_id:UUID.randomUUID().toString(),
                                         name:name,
                                         storage_date:storage_date,
                                         delivery_date:null,
                                         cost:cost,
                                         price:price,
                                         info:info]
        DBObject dbObject = ToDBObjectUtil.toDBObject(goodsInfo)
        insertOne(dbObject)
        return true
    }


    @Override
    List<DBObject> soldGoods() {
        List<DBObject> goodsList = findList(), soldList = new LinkedList<>()
        goodsList.each {
            if(it.delivery_date != null){
                soldList.add(it)
            }
        }
        return soldList
    }

    @Override
    List<DBObject> notSoldGoods() {
        List<DBObject> goodsList = findList(), notSoldList = new LinkedList<>()
        goodsList.each {
            if(it.delivery_date == null){
                notSoldList.add(it)
            }
        }
        return notSoldList
    }

    @Override
    boolean deliveryGoods(Object _id, double pay, String delivery_date, String info) {
        def goods_db = findOneById(_id)
        def goodsInfo = [_id:_id,
                         num:goods_db.num,
                         name:goods_db.name,
                         storage_date:goods_db.storage_date,
                         delivery_date:DateUtil.parseDate(delivery_date),
                         pay:pay,
                         cost:goods_db.cost,
                         price:goods_db.price,
                         info:info]as BasicDBObject
        updateOne(_id,goodsInfo)
        return true
    }

}
